<template>
  <div class="page-content">
    <!-- 表格顶部区域 -->
    <TableBar
      :columns="showColumns"
      @changeColumn="(newcolumns) => (this.columns = newcolumns)"
      :layout="layout"
    >
      <div slot="bottom">
        <el-row>
          <el-col :span="6">
            <el-button type="primary" plain size="mini" @click="dialog" v-auth="'order_customer_insert'"
              >新增</el-button
            >
          </el-col>
          <el-col :span="12">
            <el-select
              v-model="customerType"
              placeholder="请选择客户类型"
              size="mini"
              v-auth="'order_customer_select'"
            >
              <el-option
                v-for="item in [
                  { type: 'personal', label: '个人客户' },
                  { type: 'company', label: '企业客户' },
                ]"
                :key="item.type"
                :label="item.label"
                :value="item.type"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-row>
      </div>
      <div slot="top">
        <el-form label-width="55px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :lg="6">
              <el-form-item label="搜索">
                <el-input placeholder="请输入关键字" v-model="key"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="6">
              <!-- <el-form-item label="地址：">
                <el-input placeholder="地址"></el-input>
              </el-form-item> -->
            </el-col>

            <el-row
              :xs="24"
              :sm="12"
              :lg="6"
              style="float: right; margin-right: 10px"
            >
              <el-button type="primary" @click="setAllList" v-auth="'order_customer_select'">搜索</el-button>
              <el-button
                @click="
                  () => {
                    this.key = '';
                    this.setAllList();
                  }
                " v-auth="'order_customer_select'"
                >重置</el-button
              >
            </el-row>
          </el-row>
        </el-form>
      </div>
    </TableBar>
    <!-- 表格区域 -->
    <TheTable
      :data="allList"
      :page.sync="page"
      :showPage="showPage"
      @changeSize="
        (size) => {
          this.page.pageSize = size.pageSize;
          this.setAllList();
        }
      "
      @changePage="
        (page) => {
          this.page.current = page.current;
          this.setAllList();
        }
      "
      :Bottom="35"
    >
      <!-- 点击显示详情 -->
      <div class="item" effect="dark" placement="top-start">
        <el-table-column type="expand" fixed="left">
          <template slot-scope="scope">
            <el-form label-position="left" class="demo-table-expand">
              <ShowRow :columns="showColumns" :row="scope.row" num="3">
                <el-button
                  slot="slot1"
                  icon="el-icon-coordinate"
                  @click="
                    showMapCenterPoint = {
                      lat:
                        customerType === 'personal'
                          ? scope.row['customerLatitude'] || '23.12908'
                          : scope.row['companyLatitude'] || '23.12908',
                      lng:
                        customerType === 'personal'
                          ? scope.row['customerLongitude'] || '113.26436'
                          : scope.row['companyLongitude'] || '113.26436',
                      content: scope.row['receiveAddress'],
                    };
                    showMapDialog = true;
                  "
                  >地图</el-button
                >
              </ShowRow>
            </el-form>
          </template>
        </el-table-column>
      </div>
      <div
        v-for="item in showColumns"
        :key="item.id"
        class="item"
        effect="dark"
        placement="top-start"
      >
        <el-table-column
          v-if="item.show"
          :label="item.name"
          :prop="item.prop"
          show-overflow-tooltip
          :formatter="columnFormat"
          sortable
        ></el-table-column>
      </div>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            mini
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="dialog(scope.row)"
            v-auth="'order_customer_update'"
          ></el-button>
          <el-button
            mini
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delInfo(scope.row.id)"
            v-auth="'order_customer_delete'"
          ></el-button>
        </template>
      </el-table-column>
    </TheTable>
    <!-- 对话框区域 -->
    <el-dialog
      :title="dialogTitle"
      :width="customerType == 'company' ? '80%' : '50%'"
      :visible.sync="showDialog"
      top="20vh"
      @close="
        () => {
          this.showDialog = false;
          this.form = {};
        }
      "
    >
      <el-form
        label-position="right"
        ref="formRef"
        :rules="rules"
        :model="form"
        label-width="135px"
        v-if="customerType == 'company'"
      >
        <FormRow
          :form="form"
          :label-prop="formColumns.slice(0, 12)"
          num="3"
        ></FormRow>
        <el-divider></el-divider>
        <FormRow
          :form="form"
          :label-prop="formColumns.slice(12, 13)"
          num="1"
        ></FormRow>
        <FormRow
          :form="form"
          :label-prop="formColumns.slice(13, 17)"
          num="2"
        ></FormRow>
        <el-divider></el-divider>
        <FormRow
          :form="form"
          :label-prop="formColumns.slice(17, 20)"
          num="3"
        ></FormRow>
        <el-divider></el-divider>
        <FormRow
          :form="form"
          :label-prop="formColumns.slice(20, 22)"
          num="1"
        ></FormRow>
        <el-divider></el-divider>
        <FormRow
          :form="form"
          :label-prop="formColumns.slice(22)"
          num="2"
        ></FormRow>
        <el-divider></el-divider>
        <el-form-item label="收货地址" prop="receiveAddress">
          <el-select
            v-model="form.receiveAddress"
            placeholder="请选择收货地址"
            style="width: 100%"
            filterable
            :filter-method="
              (keywords) => {
                this.mapKeywordsSearch = keywords;
              }
            "
          >
            <el-option
              v-for="item in adrsOptions"
              :key="item.id"
              :label="item.address"
              :value="item.address"
              @click.native="setReceiveAddress(item)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <MyLocationPicker
          @getCenterAddress="getCenterAddress"
          @getAroundPoi="(array_pois) => (this.adrsOptions = array_pois)"
          @getInputTip="(array_tips) => (this.adrsOptions = array_tips)"
          :selectedLocation="centerLocation"
          :keywords="mapKeywordsSearch"
          :initPoint="{
            lat: this.form.receiveLatitude || '23.12908',
            lng: this.form.receiveLongitude || '113.26436',
          }"
        ></MyLocationPicker>
        <el-form-item size="large" class="dialog-bottom-btn">
          <el-button type="primary" @click="submit" v-auth="'order_customer_insert'">确定</el-button>
          <el-button @click="showDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
      <el-form
        label-position="right"
        ref="formRef"
        :rules="rules"
        :model="form"
        label-width="135px"
        v-else
      >
        <FormRow :form="form" :label-prop="formColumns" num="2"></FormRow>
        <el-divider></el-divider>
        <el-form-item label="收货地址" prop="receiveAddress">
          <el-select
            v-model="form.receiveAddress"
            placeholder="请选择收货地址"
            style="width: 100%"
            filterable
            :filter-method="
              (keywords) => {
                this.mapKeywordsSearch = keywords;
              }
            "
          >
            <el-option
              v-for="item in adrsOptions"
              :key="item.id"
              :label="item.address"
              :value="item.address"
              @click.native="setReceiveAddress(item)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <MyLocationPicker
          @getCenterAddress="getCenterAddress"
          @getAroundPoi="(array_pois) => (this.adrsOptions = array_pois)"
          @getInputTip="(array_tips) => (this.adrsOptions = array_tips)"
          :selectedLocation="centerLocation"
          :keywords="mapKeywordsSearch"
          :initPoint="{
            lat: this.form.receiveLatitude || '23.12908',
            lng: this.form.receiveLongitude || '113.26436',
          }"
        ></MyLocationPicker>
        <el-form-item size="large" class="dialog-bottom-btn">
          <el-button type="primary" @click="submit" v-auth="'order_customer_update'">确定</el-button>
          <el-button @click="showDialog = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 显示地图弹框 -->
    <ShowFile
      :dialogVisible="showMapDialog"
      :close="() => (showMapDialog = false)"
      fileType="map"
      :centerPoint="showMapCenterPoint"
    ></ShowFile>
  </div>
</template>
<script>
import {
  getAllInfoByPage,
  addInfo,
  delInfoById,
  editInfo,
} from "../../Api/ordermanage/customer_infomation";
import MyLocationPicker from "../../components/OrderManagement/Map";
import FormRow from "../../components/OrderManagement/FormRow";
import ShowRow from "../../components/OrderManagement/ShowRow";
import ShowFile from "../../components/RightsManagement/BaseFileMange/ShowFile";

export default {
  name: "CustomerInformation",
  components: {
    Map,
    MyLocationPicker,
    FormRow,
    ShowRow,
    ShowFile,
  },
  data() {
    return {
      allList: [],
      key: "",
      columns: [
        // 表头数据
        // ----------------------------------共有--------------------------------
        { name: "客户id", show: true, prop: "id" }, //show
        {
          name: "客户头像",
          show: false,
          prop: "customerAvatar",
          upload: {
            accept: "image",
          },
        }, //picture
        { name: "客户名称", show: true, prop: "customerName" },
        { name: "联系方式", show: true, prop: "contactInformation" },
        {
          name: "商务部备案编码",
          show: false,
          prop: "commerceDepartmentCoding",
        },
        { name: "收货地址", show: false, prop: "receiveAddress" }, //select
        // -------------------------------------个人--------------------------------
        { name: "客户邮箱", show: false, prop: "customerEmail" },
        { name: "客户性别", show: false, prop: "customerGender" ,select:{
          options:[
            {label:'男',value:'男'},
            {label:'女',value:'女'},
          ]
        }}, //select
        { name: "客户身份证号", show: false, prop: "customerIdNumber" },
        { name: "纬度", show: false, prop: "customerLatitude" }, //select
        { name: "经度", show: false, prop: "customerLongitude" }, //select
        // -------------------------------------企业---------------------------------
        { name: "工商注册号", show: false, prop: "businessRegistrationNumber" },
        { name: "客户企业简称", show: false, prop: "companyAbbreviation" },
        { name: "纬度", show: false, prop: "companyLatitude" }, //select
        { name: "经度", show: false, prop: "companyLongitude" }, //select
        { name: "客户企业名称", show: false, prop: "companyName" },
        { name: "法人代表", show: false, prop: "legalRepresentative" },
        { name: "经营者性质", show: false, prop: "managementCharacter",select:{
          options:[
            {label:'猪肉',value:'猪肉'},
            {label:'牛羊肉',value:'牛羊肉'},
            {label:'蔬菜',value:'蔬菜'},
            {label:'水产',value:'水产'},
            {label:'粮食',value:'粮食'},
            {label:'冷鲜禽',value:'冷鲜禽'},
            {label:'禽类',value:'禽类'},
            {label:'其他',value:'其他'},
          ]
        } }, //select
        {
          name: "经营类型",
          show: false,
          prop: "managementType",
          select: {
            options: [
              { label: "屠宰场", value: "屠宰场" },
              { label: "批发市场", value: "批发市场" },
              { label: "标准化菜市场", value: "标准化菜市场" },
              { label: "标准化超市", value: "标准化超市" },
              { label: "配送中心", value: "配送中心" },
              { label: "加工企业", value: "加工企业" },
              { label: "种植企业", value: "种植企业" },
              { label: "大卖场", value: "大卖场" },
              { label: "团体采购", value: "团体采购" },
              { label: "餐饮企业", value: "餐饮企业" },
              { label: "养殖企业", value: "养殖企业" },
              { label: "其他", value: "其他" },
            ],
          },
        }, //select
        { name: "备案日期", show: false, prop: "recordsDate" }, //date
        { name: "门店编号", show: false, prop: "storeNumber" },

        { name: "证照有效期至", show: false, prop: "credentialValidityDate" }, //date
        {
          name: "餐饮服务许可证",
          show: false,
          prop: "cateringServiceLicense",
          upload: {
            accept: "image",
          },
        }, //picture

        {
          name: "食品经营许可证",
          show: false,
          prop: "foodBusinessCertificate",
          upload: {
            accept: "image",
          },
        }, //picture
        {
          name: "食品流通许可证",
          show: false,
          prop: "foodCirculateCertificate",
          upload: {
            accept: "image",
          },
        }, //picture
        {
          name: "食品生产许可证",
          show: false,
          prop: "foodManufactureCertificate",
          upload: {
            accept: "image",
          },
        }, //picture
        {
          name: "企业认证",
          show: false,
          prop: "companyAuthentication",
          upload: {
            accept: "image",
          },
        }, //picture
        {
          name: "企业图片",
          show: false,
          prop: "companyPictures",
          upload: {
            accept: "image",
          },
        }, //picture
        {
          name: "企业微信公众号",
          show: false,
          prop: "companyWechatOfficialAccounts",
          upload: {
            accept: "image",
          },
        }, //picture
        { name: "公司简介", show: false, prop: "companyIntroduction" }, //editor
        {
          name: "企业视频",
          show: false,
          prop: "companyVideo",
          upload: {
            accept: "video",
          },
        }, //video
        { name: "企业视频名称", show: false, prop: "companyVideoName" },
      ],
      layout: "search, refresh, column",
      form: {},
      rules: {
        customerName: [
          {
            required: true,
            message: "请填写客户名称",
            trigger: "blur",
          },
        ],
        contactInformation: [
          {
            required: true,
            message: "请填写联系方式",
            trigger: "blur",
          },
        ],
        commerceDepartmentCoding: [
          {
            required: true,
            message: "请填写商务部备案编码",
            trigger: "blur",
          },
        ],
        receiveAddress: [
          {
            required: true,
            message: "请填写收货地址",
            trigger: "blur",
          },
        ],
        customerEmail: [
          {
            required: true,
            message: "请填写客户邮箱",
            trigger: "blur",
          },
        ],
        customerGender: [
          {
            required: true,
            message: "请填写客户性别",
            trigger: "blur",
          },
        ],
        customerIdNumber: [
          {
            required: true,
            message: "请填写客户身份证号",
            trigger: "blur",
          },
        ],
        businessRegistrationNumber: [
          {
            required: true,
            message: "请填写工商注册号",
            trigger: "blur",
          },
        ],
        companyAbbreviation: [
          {
            required: true,
            message: "请填写客户企业简称",
            trigger: "blur",
          },
        ],
        companyIntroduction: [
          {
            required: true,
            message: "请填写公司简介",
            trigger: "blur",
          },
        ],
        companyName: [
          {
            required: true,
            message: "请填写客户企业名称",
            trigger: "blur",
          },
        ],
        companyVideoName: [
          {
            required: true,
            message: "请填写企业视频名称",
            trigger: "blur",
          },
        ],
        credentialValidityDate: [
          {
            required: true,
            message: "请填写证照有效期至",
            trigger: "blur",
          },
        ],
        legalRepresentative: [
          {
            required: true,
            message: "请填写法人代表",
            trigger: "blur",
          },
        ],
        managementCharacter: [
          {
            required: true,
            message: "请填写经营者性质",
            trigger: "blur",
          },
        ],
        managementType: [
          {
            required: true,
            message: "请填写经营类型",
            trigger: "blur",
          },
        ],
        recordsDate: [
          {
            required: true,
            message: "请填写备案日期",
            trigger: "blur",
          },
        ],
        storeNumber: [
          {
            required: true,
            message: "请填写门店编号",
            trigger: "blur",
          },
        ],
      },
      showDialog: false,
      showPage: true, // 显示分页
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
      },
      customerType: "personal", //personal or company
      dialogTitle: "新增",
      // 选点地图
      adrsOptions: [],
      centerLocation: {},
      mapKeywordsSearch: "",
      // -----------地图弹窗----------
      showMapDialog: false,
      showMapCenterPoint: {},
    };
  },
  computed: {
    // 用于列表展示，根据customerType来判断个人或者企业
    showColumns() {
      let noArr = [];
      if (this.customerType == "personal") {
        noArr = [
          "businessRegistrationNumber",
          "cateringServiceLicense",
          "companyAbbreviation",
          "companyAuthentication",
          "companyIntroduction",
          "companyLatitude",
          "companyLongitude",
          "companyName",
          "companyPictures",
          "companyVideo",
          "companyVideoName",
          "companyWechatOfficialAccounts",
          "credentialValidityDate",
          "foodBusinessCertificate",
          "foodCirculateCertificate",
          "foodManufactureCertificate",
          "legalRepresentative",
          "managementCharacter",
          "managementType",
          "recordsDate",
          "storeNumber",
        ];
      } else {
        noArr = [
          "customerEmail",
          "customerGender",
          "customerIdNumber",
          "customerLatitude",
          "customerLongitude",
        ];
      }
      return this.columns.filter((item) => {
        return !noArr.includes(item.prop);
      });
    },
    // 过滤掉不需要在详情中展示的字段
    showRowColumns() {
      const noArr = [
        "customerLatitude",
        "customerLongitude",
        "companyLatitude",
        "companyLongitude",
      ];
      return this.columns.filter((item) => {
        return !noArr.includes(item.prop);
      });
    },
    // 过滤掉不需要用于form表单的属性
    formColumns() {
      let noArr = [];
      if (this.customerType == "personal") {
        // 去掉企业客户的字段
        noArr = [
          "businessRegistrationNumber",
          "cateringServiceLicense",
          "companyAbbreviation",
          "companyAuthentication",
          "companyIntroduction",
          "companyLatitude",
          "companyLongitude",
          "companyName",
          "companyPictures",
          "companyVideo",
          "companyVideoName",
          "companyWechatOfficialAccounts",
          "credentialValidityDate",
          "foodBusinessCertificate",
          "foodCirculateCertificate",
          "foodManufactureCertificate",
          "legalRepresentative",
          "managementCharacter",
          "managementType",
          "recordsDate",
          "storeNumber",
        ];
        // 去掉自身不需要填的字段
        noArr.push(
          "id",
          "customerLatitude",
          "customerLongitude",
          "receiveAddress"
        );
      } else {
        noArr = [
          "customerEmail",
          "customerGender",
          "customerIdNumber",
          "customerLatitude",
          "customerLongitude",
        ];
        noArr.push(
          "id",
          "companyLatitude",
          "companyLongitude",
          "receiveAddress"
        );
      }
      return this.columns.filter((item) => {
        return !noArr.includes(item.prop);
      });
    },
  },
  watch: {
    // 客户类型变化的时候
    customerType: {
      handler(customerType) {
        // console.log("customerType: ", customerType);
        this.setAllList();
      },
      immediate: true,
    },
  },
  methods: {
    // 获取数据
    async setAllList() {
      console.log("this.key: ", this.key);
      const { data: res } = await getAllInfoByPage(
        this.page.current,
        this.page.pageSize,
        this.customerType,
        this.key
      );
      if (res.statusCode !== 20000) {
        console.error(res.message);
      }
      this.allList = res.data.list;
      this.page.total = res.data.total;
    },
    // 打开弹窗
    dialog(row = undefined) {
      row instanceof Event ? (row = {}) : "";
      console.log("row: ", row);
      let form = JSON.parse(JSON.stringify(row));
      if (row.id) {
        // 修改
        this.form = form;
        this.dialogTitle = "修改";
      } else {
        // 增加
        this.dialogTitle = "新增";
      }
      this.showDialog = true;
    },
    // 提交按钮
    async submit() {
      console.log("this.form: ", this.form);
      this.$refs.formRef.validate(async (access, obj) => {
        if (access) {
          let res;
          if (!this.form.id) {
            // 增加
            res = await addInfo(this.form, this.customerType);
          } else {
            // 修改
            res = await editInfo(this.form, this.customerType);
          }
          res = res.data;
          if (res.statusCode !== 20000) {
            console.error(res.message);
            this.$message.error(res.message);
          } else {
            this.showDialog = false;
            this.$message.success(res.message);
            this.setAllList();
          }
        }
      });
    },
    // 删除按钮
    async delInfo(id) {
      this.$confirm("此操作将永久删除该信息，请谨慎操作, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await delInfoById(id, this.customerType);
          console.log("res: ", res);
          if (res.statusCode !== 20000) {
            this.$message.error(res.message);
          } else {
            this.setAllList();
            this.$message.success(res.message);
          }
        })
        .catch(() => {
          return this.$message.info("已取消删除！");
        });
    },
    // 点击下拉选择框时，设置form，地图中心点centerLocation
    setReceiveAddress(adrs) {
      // console.log("adrs: ", adrs);
      this.form.receiveAddress = adrs.address;
      if (this.customerType == "personal") {
        this.form.customerLatitude = adrs.location.lat;
        this.form.customerLongitude = adrs.location.lng;
      } else {
        this.form.companyLatitude = adrs.location.lat;
        this.form.companyLongitude = adrs.location.lng;
      }
      this.form = { ...this.form };
      this.centerLocation = adrs.location;
    },
    // 移动地图的时候，设置form
    getCenterAddress(zh_address, location, origin) {
      // console.log("location: ", location);
      // console.log("origin: ", origin);
      // console.log("zh_address: ", zh_address);
      this.form.receiveAddress = zh_address;
      if (this.customerType == "personal") {
        this.form.customerLatitude = location.lat;
        this.form.customerLongitude = location.lng;
      } else {
        this.form.companyLatitude = location.lat;
        this.form.companyLongitude = location.lng;
      }
      this.form = { ...this.form };
    },
    // 格式化表格
    columnFormat(row, columns, cellValue, index) {
      let { property } = columns;
      if (property == "customerGender") {
        return row[property] == "man" ? "男" : "女";
      }
      return row[property];
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form .el-form-item .el-input {
  width: 300px;
}
>>> .select-width {
  width: 100%;
}
.dialog-bottom-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  >>> .el-form-item__content {
    margin-left: 0 !important;
    margin-top: 20px;
  }
}
</style>